<template>
  <div class="scan-list-container">
    <!-- 页面标题与简介 -->
    <div class="page-header">
      <h2 class="page-title">扫描任务列表</h2>
      <p class="page-description">查看和管理所有扫描任务，支持筛选和排序操作</p>
    </div>
    
    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-row">
          <el-select v-model="statusFilter" placeholder="按状态筛选" clearable class="filter-item">
            <el-option label="全部状态" value="" />
            <el-option label="等待中" value="pending" />
            <el-option label="运行中" value="running" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
          
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-item"
          />
          
          <el-input
            v-model="searchQuery"
            placeholder="搜索目标或任务ID"
            clearable
            prefix-icon="el-icon-search"
            class="filter-item"
          />
          
          <el-button type="primary" @click="refreshList" class="refresh-btn">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 任务列表表格 -->
    <el-card class="scan-list-card">
      <el-table
        v-loading="loading"
        :data="paginatedScans"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="task_id" label="任务ID" width="180">
          <template #default="scope">
            <el-tooltip :content="scope.row.task_id" placement="top">
              <div class="task-id">{{ scope.row.task_id.substring(0, 12) }}...</div>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="target" label="扫描目标" min-width="200" />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-badge 
              :type="getStatusType(scope.row.status)" 
              :value="statusMap[scope.row.status]"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="scope">
            <el-progress 
              :percentage="Math.round(scope.row.progress || 0)" 
              :status="getProgressStatus(scope.row.progress)"
              show-text
              stroke-width="8"
              :format="(percentage) => `${percentage}%`"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="created_at" label="创建时间" width="160" />
        
        <el-table-column prop="completed_at" label="完成时间" width="160" />
        
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'completed'"
              type="primary" 
              size="small" 
              @click="viewResults(scope.row)"
            >
              <el-icon><Document /></el-icon>
              查看结果
            </el-button>
            <el-button 
              v-else-if="['pending', 'running'].includes(scope.row.status)"
              type="danger" 
              size="small" 
              @click="cancelScan(scope.row)"
            >
              <el-icon><Close /></el-icon>
              取消
            </el-button>
            <el-button 
              v-else-if="scope.row.status === 'failed'"
              type="warning" 
              size="small" 
              @click="retryScan(scope.row)"
            >
              <el-icon><Refresh /></el-icon>
              重试
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredScans.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 批量操作工具栏 -->
    <div v-if="selectedScans.length > 0" class="batch-actions">
      <el-card class="batch-card">
        <div class="batch-info">
          已选择 {{ selectedScans.length }} 项
        </div>
        <div class="batch-buttons">
          <el-button type="danger" @click="batchDelete" :disabled="loading">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="primary" @click="batchExport" :disabled="loading">
            <el-icon><Download /></el-icon>
            批量导出
          </el-button>
          <el-button @click="selectedScans = []">
            <el-icon><Close /></el-icon>
            取消选择
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import { Refresh, Document, Close, Delete, Download } from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'

const router = useRouter()
const loading = ref(false)
const scans = ref([])
const selectedScans = ref([])
const statusFilter = ref('')
const dateRange = ref(null)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 状态映射
const statusMap = {
  'pending': '等待中',
  'running': '运行中',
  'completed': '已完成',
  'failed': '失败'
}

// 根据状态获取类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return typeMap[status] || 'info'
}

// 根据进度获取状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success'
  if (progress > 0) return 'warning'
  return 'info'
}

// 筛选后的扫描列表
const filteredScans = computed(() => {
  return scans.value.filter(scan => {
    // 状态筛选
    if (statusFilter.value && scan.status !== statusFilter.value) return false
    
    // 日期范围筛选
    if (dateRange.value && dateRange.value.length === 2) {
      const scanDate = new Date(scan.created_at)
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      endDate.setHours(23, 59, 59, 999)
      if (scanDate < startDate || scanDate > endDate) return false
    }
    
    // 搜索筛选
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      return scan.target.toLowerCase().includes(query) || 
             scan.task_id.toLowerCase().includes(query)
    }
    
    return true
  })
})

// 分页后的扫描列表
const paginatedScans = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredScans.value.slice(start, end)
})

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedScans.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 刷新列表
const refreshList = async () => {
  await loadScans()
}

// 加载扫描列表
const loadScans = async () => {
  loading.value = true
  try {
    // 尝试获取真实数据
    console.log('正在获取真实扫描列表数据...')
    
    // 构建查询参数，支持筛选和搜索
    const params = {}
    if (statusFilter.value) params.status = statusFilter.value
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    if (searchQuery.value) params.keyword = searchQuery.value
    
    // 调用API获取扫描结果
    const response = await apiService.getScanResults(params)
    
    // 检查响应数据并进行适当处理
    if (response && response.success && response.data) {
      // 标准化API返回的数据格式，确保与表格期望的格式一致
      let apiScans = response.data
      
      // 如果返回的是数组，直接使用；如果是对象，提取items字段
      if (!Array.isArray(apiScans)) {
        apiScans = apiScans.items || apiScans.scans || []
      }
      
      // 数据格式转换和标准化
      scans.value = apiScans.map(scan => ({
        task_id: scan.task_id || scan.id || `task-${Math.random().toString(36).substring(2, 10)}`,
        target: scan.target || scan.url || '未知目标',
        status: scan.status || 'pending',
        progress: scan.progress !== undefined ? scan.progress : 
                 (scan.status === 'completed' ? 100 : scan.status === 'failed' ? 0 : 0),
        created_at: scan.created_at ? formatDate(scan.created_at) : new Date().toLocaleString('zh-CN'),
        completed_at: scan.completed_at ? formatDate(scan.completed_at) : '-',
        scan_depth: scan.scan_depth || scan.depth || 1,
        scan_types: scan.scan_types || scan.types || ['general']
      }))
      
      console.log('成功获取并处理真实扫描数据，共', scans.value.length, '条记录')
    } else {
      // 响应格式不正确时使用模拟数据
      console.warn('API返回数据格式不符合预期，使用模拟数据')
      scans.value = getMockScans()
    }
  } catch (error) {
    console.error('获取扫描列表失败:', error.message || error)
    // 使用模拟数据作为后备
    scans.value = getMockScans()
    ElMessage.warning('无法获取真实数据，使用模拟数据')
  } finally {
    loading.value = false
  }
}

// 日期格式化辅助函数
const formatDate = (dateString) => {
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return '-'
    }
    return date.toLocaleString('zh-CN')
  } catch (e) {
    return '-'
  }
}

// 查看结果
const viewResults = (scan) => {
  router.push({ path: '/results', query: { taskId: scan.task_id } })
}

// 取消扫描
const cancelScan = async (scan) => {
  try {
    await apiService.cancelScan(scan.task_id)
    ElMessage.success('扫描已取消')
    await loadScans()
  } catch (error) {
    ElMessage.error('取消扫描失败')
  }
}

// 重试扫描
const retryScan = async (scan) => {
  try {
    await apiService.retryScan(scan.task_id)
    ElMessage.success('扫描已重新开始')
    await loadScans()
  } catch (error) {
    ElMessage.error('重试扫描失败')
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    const taskIds = selectedScans.value.map(scan => scan.task_id)
    await apiService.batchDeleteScans(taskIds)
    ElMessage.success(`已删除 ${selectedScans.value.length} 个任务`)
    selectedScans.value = []
    await loadScans()
  } catch (error) {
    ElMessage.error('批量删除失败')
  }
}

// 批量导出
const batchExport = async () => {
  try {
    const taskIds = selectedScans.value.map(scan => scan.task_id)
    await apiService.exportScans(taskIds)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 生成模拟数据
const getMockScans = () => {
  const statuses = ['pending', 'running', 'completed', 'failed']
  const targets = [
    'http://example.com',
    'http://test-site.org',
    'https://secure-app.net',
    '192.168.1.100',
    'https://api-demo.com'
  ]
  
  const scans = []
  for (let i = 1; i <= 20; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const createdTime = new Date()
    createdTime.setMinutes(createdTime.getMinutes() - Math.floor(Math.random() * 1000))
    
    scans.push({
      task_id: `task-${Math.random().toString(36).substring(2, 10)}`,
      target: targets[Math.floor(Math.random() * targets.length)],
      status,
      progress: status === 'completed' ? 100 : status === 'failed' ? 0 : Math.floor(Math.random() * 100),
      created_at: createdTime.toLocaleString('zh-CN'),
      completed_at: status === 'completed' ? new Date().toLocaleString('zh-CN') : '-',
      scan_depth: Math.floor(Math.random() * 5) + 1,
      scan_types: ['sql_injection', 'xss', 'info_leak']
    })
  }
  
  // 按创建时间倒序排列
  return scans.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
}

// 组件挂载时加载数据
onMounted(() => {
  loadScans()
})
</script>

<style scoped>
.scan-list-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.page-description {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 12px;
  overflow: hidden;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  min-width: 180px;
}

.scan-list-card {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 24px;
}

.task-id {
  font-family: monospace;
  color: #3498db;
  cursor: pointer;
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  left: 20px;
  max-width: 1200px;
  margin: 0 auto;
  z-index: 100;
}

.batch-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.batch-info {
  font-weight: 600;
  color: #2c3e50;
}

.batch-buttons {
  display: flex;
  gap: 12px;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .batch-card {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .batch-buttons {
    width: 100%;
    justify-content: space-between;
  }
}
</style>